package com.yq.homework.day281;

import java.io.*;

/**
 * @author 3307235355@qq.com
 * @since 2022/06/28 19:40
 * 使用多线程实现方式二的方式,完成文件复制,显示百分比
 */
public class Demo02 {
    public static void main(String[] args) {
        MyThread1 m1 = new MyThread1("a.txt","copy_a.txt");
        MyThread1 m2 = new MyThread1("b.txt","copy_b.txt");
        MyThread1 m3 = new MyThread1("c.txt","copy_c.txt");
        new Thread(m1).start();
        new Thread(m2).start();
        new Thread(m3).start();

    }
}
class MyThread1 implements Runnable{
    File oldFile;
    File newFile;
    public MyThread1(String oldFile, String newFile) {
        this.oldFile = new File(oldFile);
        this.newFile = new File(newFile);
    }

    @Override
    public void run() {
        // 复制文件操作
        try(FileInputStream in = new FileInputStream(oldFile);
            FileOutputStream out = new FileOutputStream(newFile)) {

            // 边读边写
            int readCount;
            byte[] bytes = new byte[1024];
            // 用来做累加的
            double temp = 0;
            long length = oldFile.length();
            while ((readCount = in.read(bytes)) != -1) {
                // write
                out.write(bytes);
                temp += readCount;
                double persent = temp / length * 100;
                System.out.println(oldFile + "复制了:"+String.format("%.2f",persent)+"%");
            }
            System.out.println(oldFile + "复制完成!");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}